import React from 'react';
import routes from './routes';
import PropTypes from 'prop-types';
import {Button, Modal} from 'antd';
import {importTemp, importData} from './api';
import {formatMessage, injectIntl} from './intl';
import ExcelImportIntl from '../common/ExcelImportIntl';

const basePath = fetch.basePath || '';

class ImportPanel extends React.PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
        };
    }
    afterUpload = file => {
        if(file.ok)
            // eslint-disable-next-line array-callback-return
            file.response.payload.content.map(v => {
                if(v.vin)
                    Modal.confirm({
                        title: formatMessage({
                            id: 'importPanel.message.switch',
                            defaultMessage: '提示'
                        }),
                        content: formatMessage({
                            id: 'importPanel.message.switchVin',
                            defaultMessage: '模板中的VIN将覆盖发运单中已存在的VIN，是否继续？'
                        }),
                        onOk: () => {
                            importData(file.response.payload.content).then(res => {
                                if(res.ok)
                                    this.props.successReturn();
                            });
                        }
                    });
            });
    }
    render() {
        return (
            [
                <div key="return" className="page-toolbar">
                    <Button type="primary" href={`#${routes.query.url()}`} disabled={this.state.loading}>
                        {formatMessage({
                            id: 'importPanel.btm.return',
                            defaultMessage: '返回'
                        })}
                    </Button>
                </div>,
                <ExcelImportIntl
                    key="import"
                    action={`${basePath}/sales/api/v1/CBUSaleShipments/importInfo`}
                    template={importTemp}
                    templateName={formatMessage({
                        id: 'importPanel.show.importCBUSaleShipments',
                        defaultMessage: 'CBU整车发运单导入模板'
                    })}
                    afterUpload={this.afterUpload} />
            ]
        );
    }
}

ImportPanel.propTypes = {
    successReturn: PropTypes.func.isRequired,
    history: PropTypes.object,
    onCancel: PropTypes.func,
};
import {connect} from 'react-redux';
import {querySearch} from './actions';
const mapDispatchToProps = (dispatch, props) => ({
    successReturn: () => {
        dispatch(querySearch());
        props.history.push(routes.query.url());
    }
});
export default connect(null, mapDispatchToProps)(injectIntl(ImportPanel));
